package com.shenmazong.servertalkmarket.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.pojo.TbMarketCoupon;
import com.shenmazong.servertalkmarket.mapper.TbMarketCouponMapper;
import com.shenmazong.utils.ConstUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@EnableScheduling
@Component
public class CouponTask {

    @Autowired
    private TbMarketCouponMapper tbMarketCouponMapper;

    @Autowired
    RedisTemplate redisTemplate;

    // 秒 分钟 小时 天 月 星期 年份
    @Scheduled(cron = "* 30 20 * * *")
    public void beginCouponTask() {
        //--1 检查优惠信息
        TbMarketCoupon marketCoupon = tbMarketCouponMapper.selectOne(
                new QueryWrapper<TbMarketCoupon>()
                        .eq("status", 0)
                        .orderByDesc("create_time")
                        .last("limit 1")
        );
        if(marketCoupon == null) {
            log.info("没有特惠活动");
            return;
        }

        //--2 生产优惠券，放入redis
        // 循环加入优惠券
        for (int idx = 0; idx < marketCoupon.getClassCount(); idx++) {
            redisTemplate.opsForList().leftPush(ConstUtils.WAITING_COUPON_KEY, marketCoupon.getId());
        }
        // 设置优惠券的过期时间
        redisTemplate.expire(ConstUtils.WAITING_COUPON_KEY, 1, TimeUnit.HOURS);

        // 设置以抢到优惠券用户集合的时间
        redisTemplate.opsForSet().add(ConstUtils.CATCH_COUPON_KEY, 0);
        redisTemplate.expire(ConstUtils.CATCH_COUPON_KEY, 1, TimeUnit.HOURS);

        //--3 修改优惠活动的状态
        marketCoupon.setStatus(1);
        tbMarketCouponMapper.updateById(marketCoupon);

        //
        System.out.println("开始抢购了");
    }
}
